package org.itboys.mobile.service.mongo.mobile.common;


import org.itboys.commons.utils.random.RandomUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayCode;
import org.itboys.mobile.util.PhoneUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_验证码_service
 */
@Service
public class SundayMobileCodeService extends BaseMongoService<SundayCode> {
    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }

    @Override
    protected Class<SundayCode> getEntityClass() {
        return SundayCode.class;
    }
    /**
     * 发送验证码
     * @param mobile
     * @param type
     */
    public int sendCode(String mobile,Integer type){
        int resultCode=0;

        //校验手机号是否合法
        if(!PhoneUtil.isMobileNumber(mobile)){
            //   resultCode=;
            return -2;
        }
        //删除原有的验证码
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("mobile",mobile);
        param.put("type",type);
        super.delete(param);
        //保存验证码记录
        String code = RandomUtils.getIntRandom(6);
        System.out.println("当前验证码=="+code);
        super.save( new SundayCode(mobile,code,type));
        //发送验证码

        return resultCode;
    }

    /**
     *
     * @param mobile
     * @param type
     * @return
     */
    /**
     * 校验艳照门
     * @param mobile
     * @param code
     * @param type
     * @return
     */
    public int checkCode(String mobile,String code,Integer type){
        int resultCode=0;
        //校验手机号是否合法
        if(!PhoneUtil.isMobileNumber(mobile)){
            return -2;
        }
        //校验验证码
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("mobile",mobile);
        param.put("type",type);
        List<SundayCode> oldCodes = super.list(param);
        if(ListUtil.isNull(oldCodes)){
            return -1;
        }
        String oldCode = oldCodes.get(0).getCode();
        //验证码错误
        if(!code.equalsIgnoreCase(code)){
            return -3;
        }
        return resultCode;
    }


}
